<template>
    <div>
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item> <i class="el-icon-lx-calendar"></i> 员工管理 </el-breadcrumb-item>
                <el-breadcrumb-item>员工修改</el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <div class="container">
            <div class="form-box">
                <el-form ref="form" :model="form" label-width="80px" :rules="rules">
                    <el-divider content-position="left">基础信息</el-divider>

                    <el-form-item label="员工姓名" prop="name">
                        <el-input v-model="form.name" disabled></el-input>
                    </el-form-item>

                    <el-row>
                        <el-col :span="11">
                            <el-form-item label="员工号" prop="tellerId">
                                <el-input v-model="form.tellerId" disabled></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="11">
                            <el-form-item label="职位" prop="position">
                                <el-select v-model="form.pid" clearable placeholder="职位">
                                    <el-option key="00" value="00" label="暂无职位"></el-option>
                                    <el-option v-for="(item, index) in positions" :key="index" :label="item.name" :value="item.id">
                                    </el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                    </el-row>

                    <el-form-item label="身份证号" prop="idCard" style="width: 70%">
                        <el-input v-model="form.idCard" onkeyup="this.value=this.value.replace(/[^\X0-9]/g, '')" disabled> </el-input>
                    </el-form-item>

                    <el-form-item label="学历" prop="education">
                        <el-select v-model="form.education" clearable placeholder="学历">
                            <el-option v-for="item in educations" :key="item" :label="item" :value="item"> </el-option>
                        </el-select>
                    </el-form-item>

                    <el-form-item label="性别" prop="sex">
                        <el-radio v-model="form.sex" label="01" border size="medium">男</el-radio>
                        <el-radio v-model="form.sex" label="00" border size="medium">女</el-radio>
                    </el-form-item>

                    <el-form-item label="出生日期" prop="birthday">
                        <el-date-picker
                            v-model="form.birthday"
                            type="date"
                            format="yyyy-MM-dd"
                            placeholder="选择日期"
                            :picker-options="pickerOptions"
                            @change="setAge"
                        >
                        </el-date-picker>
                    </el-form-item>

                    <el-divider content-position="left">联系方式</el-divider>

                    <el-form-item label="手机号码" prop="phone" style="width: 50%">
                        <el-input v-model="form.phone"></el-input>
                    </el-form-item>

                    <el-form-item label="邮箱" prop="email" style="width: 60%">
                        <el-input v-model="form.email"></el-input>
                    </el-form-item>

                    <el-divider content-position="left">家庭信息</el-divider>

                    <el-form-item label="家人姓名" prop="family" style="width: 40%">
                        <el-input v-model="form.family"></el-input>
                    </el-form-item>

                    <el-form-item label="联系方式" prop="fphone" style="width: 50%">
                        <el-input v-model="form.fphone"></el-input>
                    </el-form-item>

                    <el-form-item label="家庭住址" prop="address">
                        <el-input v-model="form.address"></el-input>
                    </el-form-item>

                    <el-divider content-position="left">员工状态</el-divider>

                    <el-form-item label="状态" prop="status">
                        <el-switch
                            v-model="form.status"
                            active-value="01"
                            active-text="正常"
                            inactive-value="00"
                            inactive-text="离职"
                        ></el-switch>
                    </el-form-item>

                    <el-form-item>
                        <el-button @click="goback" icon="el-icon-arrow-left">返回</el-button>
                        <el-button type="primary" @click="onSubmit('form')" icon="el-icon-plus">修改</el-button>
                        <el-button type="warning" @click="reset('form')" icon="el-icon-refresh-right">重置</el-button>
                    </el-form-item>
                </el-form>
            </div>
        </div>
    </div>
</template>

<script>
export default {
    name: 'baseform',
    inject: ['reload'],
    data() {
        // 邮箱验证
        var checkEmail = (rule, value, callback) => {
            if (!value) {
                callback();
            }
            if (!/^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/.test(value)) {
                callback(new Error('邮箱格式错误'));
            } else {
                callback();
            }
        };

        /**验证手机信息 */
        var checkPhone = (rule, value, callback) => {
            if (!value) {
                return callback(new Error('手机号不能为空'));
            }
            if (!/^((1[3,5,8,7,9][0-9])|(14[5,7])|(17[0,6,7,8])|(19[7]))\d{8}$/.test(value)) {
                callback(new Error('手机号格式错误'));
            } else {
                callback();
            }
        };

        /*验证身份证格式*/
        var checkIdentitytionId = (rule, value, callback) => {
            if (!value) {
                return callback(new Error('身份证号不能为空'));
            }
            if (!/(^\d{15}$)|(^\d{17}(\d|X|x)$)/.test(value)) {
                callback(new Error('你输入的身份证长度或格式错误'));
            }
            //身份证城市
            var aCity = {
                11: '北京',
                12: '天津',
                13: '河北',
                14: '山西',
                15: '内蒙古',
                21: '辽宁',
                22: '吉林',
                23: '黑龙江',
                31: '上海',
                32: '江苏',
                33: '浙江',
                34: '安徽',
                35: '福建',
                36: '江西',
                37: '山东',
                41: '河南',
                42: '湖北',
                43: '湖南',
                44: '广东',
                45: '广西',
                46: '海南',
                50: '重庆',
                51: '四川',
                52: '贵州',
                53: '云南',
                54: '西藏',
                61: '陕西',
                62: '甘肃',
                63: '青海',
                64: '宁夏',
                65: '新疆',
                71: '台湾',
                81: '香港',
                82: '澳门',
                91: '国外'
            };
            if (!aCity[parseInt(value.substr(0, 2))]) {
                callback(new Error('你的身份证地区非法'));
            }
            // 出生日期验证
            var sBirthday = value.substr(6, 4) + '-' + Number(value.substr(10, 2)) + '-' + Number(value.substr(12, 2)),
                d = new Date(sBirthday);
            if (sBirthday != d.getFullYear() + '-' + (d.getMonth() + 1) + '-' + d.getDate()) {
                callback(new Error('身份证上的出生日期非法'));
            }

            // 身份证号码校验
            var sum = 0,
                weights = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2],
                codes = '10X98765432';
            for (var i = 0; i < value.length - 1; i++) {
                sum += value[i] * weights[i];
            }
            var last = codes[sum % 11]; //计算出来的最后一位身份证号码
            if (value[value.length - 1] != last) {
                callback(new Error('你输入的身份证号非法'));
            }
            this.form.birthday = sBirthday;
            this.setAge(d);
            callback();
        };

        return {
            pickerOptions: {
                disabledDate(time) {
                    var d = new Date();
                    var legalTime = d.getFullYear() - 18 + '-' + (d.getMonth() + 1) + '-' + d.getDate();
                    return time.getTime() > new Date(legalTime);
                }
            },
            educations: [],
            positions: [],
            employee: {},
            id: this.$route.query.id,
            form: {
                id: '',
                tellerId: '',
                idCard: '',
                pid: '',
                name: '',
                age: '',
                sex: '',
                education: '',
                birthday: '',
                address: '',
                phone: '',
                email: '',
                family: '',
                fphone: '',
                status: '01'
            },
            condition: {
                did: '00',
                status: '01'
            },
            rules: {
                name: [
                    { required: true, message: '请输入员工姓名', trigger: 'blur' },
                    { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
                ],
                education: [{ required: true, message: '请选择学历', trigger: 'blur' }],
                sex: [{ required: true, message: '请选择性别', trigger: 'blur' }],
                birthday: [{ required: true, message: '请选择出生日期', trigger: 'blur' }],
                idCard: [{ validator: checkIdentitytionId, required: true, trigger: 'blur' }],
                phone: [{ validator: checkPhone, required: true, trigger: 'blur' }],
                email: [{ validator: checkEmail, trigger: 'blur' }],
                family: [{ required: true, message: '请输入家庭成员姓名', trigger: 'blur' }],
                fphone: [{ validator: checkPhone, required: true, trigger: 'blur' }]
            }
        };
    },
    created: function () {
        this.getEducations();
        this.getPositions();
        this.getEmployee();
    },
    methods: {
        setAge(time) {
            var nowTime = new Date();
            var age = nowTime.getFullYear() - time.getFullYear();
            if (time.getMonth() < nowTime.getMonth()) {
                this.form.age = age;
            } else if (time.getMonth() > nowTime.getMonth()) {
                this.form.age = age - 1;
            } else if (time.getDate() > nowTime.getDate()) {
                this.form.age = age - 1;
            } else {
                this.form.age = age;
            }
        },
        init() {
            this.form.id = this.id;
            this.form.name = this.employee.name;
            this.form.tellerId = this.employee.tellerId;
            this.form.phone = this.employee.phone;
            this.form.email = this.employee.email;
            this.form.family = this.employee.family;
            this.form.fphone = this.employee.fphone;
            this.form.status = this.employee.status;
            this.form.pid = this.employee.pid;
            this.form.age = this.employee.age;
            this.form.sex = this.employee.sex;
            this.form.idCard = this.employee.idCard;
            this.form.birthday = this.employee.birthday;
            this.form.education = this.employee.education;
            this.form.address = this.employee.address;
        },
        async getEmployee() {
            var d = await this.$http.get('/employee/' + this.id);
            if (d.code == 200) {
                this.employee = d.data;
                this.init();
                console.log(this.employee);
            }
        },

        getEducations() {
            this.educations = JSON.parse(window.sessionStorage.getItem('education'));
        },

        async getPositions() {
            this.condition.did = '';
            this.condition.status = '01';
            var d = await this.$http.post('/positionMap', this.condition);
            if (d.code == 200) {
                this.positions = d.data;
            }
            console.log(this.positions);
        },

        onSubmit(formName) {
            this.$refs[formName].validate(async (valid) => {
                if (valid) {
                    var d = await this.$http.put('/employee', this.form);
                    if (d.code == 200) {
                        this.$message.success(d.message);
                    } else {
                        this.$message.error(d.message);
                    }
                } else {
                    this.$message.warning('请把内容填写完整!');
                }
            });
        },

        goback(){
            this.$router.go(-1);
        },

        reset(formName) {
            this.$confirm('此操作将重置所有信息, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            })
                .then(() => {
                    this.init();
                })
                .catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消重置'
                    });
                });
        }
    }
};
</script>